(:
 : This application provides an interface to multiple (social) media sources with XQuery.
:)
 
module namespace flightSearch = "http://www.xmlproject.com/smi/flightSearch";

import module namespace http = "http://www.28msec.com/modules/http";

(: CONTROLLER :)
import module namespace search = "http://www.xmlproject.com/smi/lib/controller/search";

(: VIEW :)
import module namespace mainview = "http://www.xmlproject.com/smi/lib/view/mainview";
import module namespace resultview = "http://www.xmlproject.com/smi/lib/view/resultview";


(:~
 : handler for the project's start page  
 :
 : @return returns the HTML start page
 :)

declare function flightSearch:index.xq () as item() 
{
    (: show the start page :)
    mainview:show()
};


(:~
 : handler for the search api. Pass the search term as query parameter.  
 :
 : @return returns the search results from eBay and Amazon rendered in an HTML table 
:)
declare sequential function flightSearch:search() {
    declare $query as xs:string := if(empty(http:get-parameters("query")[1]))
                                   then ""
                                   else xs:string(http:get-parameters("query")[1]);
                                   
    (: make sure query is not empty :)
    if ($query = "")
    then 
        block
        {
            
            (: signal Bad Request Error :)
            http:set-status(400); 
            
            http:set-content-type("text/html");
            
            (: this is the xml representation of JSON which makes it easy to generate it, 
               and work with it within sausalito :)
            <json type="object">
                <pair name="status" type="number">400</pair>
                <pair name="statusmessage" type="string">Bad Request</pair>
                <pair name="message" type="string">Please, enter a search term</pair>
            </json>;
        }
    else 
        block
        {
            (: browsers should not cache the results :)
            http:set-header("Cache-Control", "no-cache"),
            
            (: with the content type "application/jsonml+json" sausalito
               automatically serializes any xml to jsonml :)
            http:set-content-type("text/html");
    
            (: ask expedia for the results for the query :)
            let $expediaResults := search:expedia($query)
            
            (: get the HTML result table for the results :)
            return resultview:show($expediaResults,$expediaResults);                 
        }
};